{% extends "button.html" %}
{% block title %}
    <title>样本临床信息</title>
{% endblock %}


{% block content %}
    <div class="jumbotron">
        <h1>甲基化早筛项目数据库管理系统Demo</h1>
        <h4>样本临床信息表</h4>
    </div>
{% endblock %}

{% block plot %}
    <div class="row">
        <div id="plot_highcharts" style="width: 550px; height: 400px; margin: 0 auto" class="col-9"></div>
        <div id="plot_button" class="form-group col-3">
            <label for="plot_highcharts_field"> 请选择用于画图的关键字段</label>
            <select class="form-control" id="plot_highcharts_field" name="plot_highcharts_field">
                <option value="gender" selected="selected">性别</option>
                <option value="age">年龄</option>
                <option value="category">癌种</option>
                <option value="diagnose">诊断</option>
                <option value="centrifugation_date">采样日期</option>
                <option value="hospital">医院编号</option>
                <option value="send_date">寄送日期</option>
            </select>
        </div>
    </div><br>
{% endblock %}

{% block table %}
    <!-- datatables -->
    <table id="table_id" class="display">
        <thead>
        <tr>
            <th>索引</th>
            <th>样本编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>住院号</th>
            <th>癌种</th>
            <th>分期</th>
            <th>诊断</th>
            <th>诊断备注</th>
            <th>采样日期</th>
            <th>医院编号</th>
            <th>科室</th>
            <th>血浆管数</th>
            <th>癌旁组织样本数量</th>
            <th>癌组织样本数量</th>
            <th>白细胞样本数量</th>
            <th>粪便样本数量</th>
            <th>寄送日期</th>
            <th>备注</th>
            <th>上次修改时间</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
    </table>
{% endblock %}

{% block ModalForm %}
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
            <label for="sample_id"> 样本编号</label></span>
        <input type="text" class="form-control" id="sample_id" name="sample_id"
               placeholder="请输入样本编号，必填" required="true">
    </div>
    <div class="form-group">
        <label for="name"> 姓名</label>
        <input type="text" class="form-control" id="name" name="name"
               placeholder="请输入姓名，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="gender"> 性别</label>
        <select class="form-control" id="gender" name="gender">
            <option value="男" selected="selected">男</option>
            <option value="女">女</option>
        </select>
    </div>
    <div class="form-group">
        <label for="age"> 年龄</label>
        <input type="text" class="form-control" id="age" name="age"
               placeholder="请输入年龄，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="patientId"> 住院号</label>
        <input type="text" class="form-control" id="patientId" name="patientId"
               placeholder="请输入住院号，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="category"> 癌种</label>
        <input type="text" class="form-control" id="category" name="category"
               placeholder="请输入癌种信息，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="stage"> 分期</label>
        <input type="text" class="form-control" id="stage" name="stage"
               placeholder="请输入分期信息，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="diagnose"> 诊断</label>
        <input type="text" class="form-control" id="diagnose" name="diagnose"
               placeholder="请输入诊断信息，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="diagnose_others"> 诊断备注</label>
        <input type="text" class="form-control" id="diagnose_others" name="diagnose_others"
               placeholder="请输入诊断备注信息，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="centrifugation_date"> 采样日期</label>
        <input type="date" class="form-control" id="centrifugation_date" name="centrifugation_date"
               placeholder="请输入采样日期，默认：2000-01-01" value="2000-01-01">
    </div>
    <div class="form-group">
        <label for="hospital"> 医院编号</label>
        <input type="text" class="form-control" id="hospital" name="hospital"
               placeholder="请输入医院编号，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="department"> 科室</label>
        <input type="text" class="form-control" id="department" name="department"
               placeholder="请输入科室，默认：无" value="无">
    </div>
    <div class="form-group">
        <label for="plasma_num"> 血浆管数</label>
        <input type="text" class="form-control" id="plasma_num" name="plasma_num"
               placeholder="默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="adjacent_mucosa_num"> 癌旁组织数量</label>
        <input type="text" class="form-control" id="adjacent_mucosa_num" name="adjacent_mucosa_num"
               placeholder="默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="cancer_tissue_num"> 癌组织数量</label>
        <input type="text" class="form-control" id="cancer_tissue_num" name="cancer_tissue_num"
               placeholder="默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="WBC_num"> 白细胞数量</label>
        <input type="text" class="form-control" id="WBC_num" name="WBC_num"
               placeholder="默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="stool_num"> 粪便数量</label>
        <input type="text" class="form-control" id="stool_num" name="stool_num"
               placeholder="默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="send_date"> 寄送日期</label>
        <input type="date" class="form-control" id="send_date" name="send_date"
               placeholder="请输入寄送日期，默认：2000-01-01" value="2000-01-01">
    </div>
    <div class="form-group">
        <label for="others"> 备注</label>
        <input type="text" class="form-control" id="others" name="others"
               placeholder="请输入备注，默认：无" value="无">
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        $(document).ready(function () {
            let url = '/api/ClinicalInfo/';
            let id = 0;
            let dataModelForm; //更新弹窗默认值，重置按钮需要
            let fieldForPie = $('#plot_highcharts_field');

            function MyModelInit(title_name, data) {
                dataModelForm = data;
                if (title_name === '更新') {
                    $('#sample_id').val(data['sample_id']);
                    $('#name').val(data['name']);
                    $('#gender').val(data['gender']);
                    $('#age').val(data['age']);
                    $('#patientId').val(data['patientId']);
                    $('#category').val(data['category']);
                    $('#stage').val(data['stage']);
                    $('#diagnose').val(data['diagnose']);
                    $('#diagnose_others').val(data['diagnose_others']);
                    $('#centrifugation_date').val(data['centrifugation_date']);
                    $('#hospital').val(data['hospital']);
                    $('#department').val(data['department']);
                    $('#plasma_num').val(data['plasma_num']);
                    $('#adjacent_mucosa_num').val(data['adjacent_mucosa_num']);
                    $('#cancer_tissue_num').val(data['cancer_tissue_num']);
                    $('#WBC_num').val(data['WBC_num']);
                    $('#stool_num').val(data['stool_num']);
                    $('#send_date').val(data['send_date']);
                    $('#others').val(data['others']);
                    $('#type').val('edit');
                    $('#modal_title').text('更新');
                } else {
                    $('#sample_id').val("");
                    $('#name').val("");
                    $('#gender option:first').prop("selected", 'selected');
                    $('#age').val("");
                    $('#patientId').val("");
                    $('#category').val("");
                    $('#stage').val("");
                    $('#diagnose').val("");
                    $('#diagnose_others').val("");
                    $('#centrifugation_date').val("2000-01-01");
                    $('#hospital').val("");
                    $('#department').val("");
                    $('#plasma_num').val("");
                    $('#adjacent_mucosa_num').val("");
                    $('#cancer_tissue_num').val("");
                    $('#WBC_num').val("");
                    $('#stool_num').val("");
                    $('#send_date').val("2000-01-01");
                    $('#others').val("");
                    $('#type').val('new');
                    $('#modal_title').text('新增');
                }
            }

            let table = $('#table_id').DataTable({
                "language": {
                    "lengthMenu": "选择每页 _MENU_ 展示 ",
                    "zeroRecords": "未找到匹配结果--抱歉",
                    "info": "当前显示第 _PAGE_ 页结果，共 _PAGES_ 页",
                    "infoEmpty": "没有数据",
                    "search": "搜索",
                    "infoFiltered": "(获取 _MAX_ 项结果)",
                    "paginate": {
                        "first": "首页",
                        "previous": "上一页",
                        "next": "下一页",
                        "last": "末页"
                    }
                },
                "scrollY": "5000px",
                "scrollCollapse": true,
                "scrollX": true,
                "pagingType": "full_numbers",
                fixedColumns: true,
                rowReorder: true,
                colReorder: true,
                searching: true,
                select: true,
                dom: 'lB<"clear">frtip',
                buttons: [
                    {
                        extend: 'colvisGroup',
                        text: '显示前5列',
                        show: [0, 1, 2, 3, 4, 5, 22],
                        hide: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
                    },
                    {
                        extend: 'colvisGroup',
                        text: '显示全部列',
                        show: ':hidden',
                    },
                    {
                        text: '指定显示列', extend: 'colvis',
                        postfixButtons: ['colvisRestore'],
                        columnText: function (dt, idx, title) {
                            return (idx + 1) + ': ' + title;
                        }
                    },
                    {
                        extend: 'selectAll',
                        text: '全选'
                    }, {
                        extend: 'selectRows',
                        text: '选择多行'
                    }, {
                        extend: 'selectNone',
                        text: '取消当前选择'
                    },
                    {
                        extend: 'copy',
                        text: '复制到剪切板',
                        exportOptions: {
                            columns: range(1, 21)
                        }
                    }, {
                        extend: 'csv',
                        text: '输出到csv',
                        exportOptions: {
                            columns: range(1, 21)
                        }
                    }
                ],
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "serverSide": true,
                "processing": true,
                "ajax": "/api/ClinicalInfo/?format=datatables",
                "deferRender": true,
                "columns": [
                    {
                        data: 'index',
                        width: "1%",
                        // 若想前端显示的不一样，则需要"render"函数
                        'render': function (data, type, full, meta) {
                            return meta.row + 1 + meta.settings._iDisplayStart;
                        }
                    },
                    {"data": "sample_id"},
                    {"data": "name"},
                    {"data": "gender"},
                    {"data": "age"},
                    {"data": "patientId"},
                    {"data": "category"},
                    {"data": "stage"},
                    {"data": "diagnose"},
                    {"data": "diagnose_others"},
                    {"data": "centrifugation_date"},
                    {"data": "hospital"},
                    {"data": "department"},
                    {"data": "plasma_num"},
                    {"data": "adjacent_mucosa_num"},
                    {"data": "cancer_tissue_num"},
                    {"data": "WBC_num"},
                    {"data": "stool_num"},
                    {"data": "send_date"},
                    {"data": "others"},
                    {"data": "last_modify_date"},
                    {"data": "created"},
                    {
                        "data": null,
                        "defaultContent": '<button type="button" class="btn btn-info">更新</button>' + '&nbsp;&nbsp' +
                            '<button type="button" class="btn btn-danger">删除</button>'
                    }
                ]
            });
            table.button(0).trigger();

            $('#table_id tbody').on('click', 'button', function () {
                let data = table.row($(this).parents('tr')).data();
                let class_name = $(this).attr('class');
                id = data['index'];
                //alert(id);
                if (class_name === 'btn btn-info') {
                    // EDIT button
                    MyModelInit('更新', data);
                    $("#myModal").modal();
                } else {
                    // DELETE button
                    //alert('delete '+id);
                    //$('#modal_title').text('DELETE');
                    $("#confirm").modal();
                }

            });

            $('#modelForm').on('submit', function (e) {
                e.preventDefault();
                // 递交前检查，一般是检测model的外键是否存在

                let type = $('#type').val();
                let method = '';
                let url_ajax = url;
                if (type === 'new') {
                    // new
                    method = 'POST';
                    // POST前检查，一般是检测model的关键字段值是否存在
                    let data0 = $.ajax({
                        url: url, dataType: 'json', contentType: "application/json",
                        type: "get", async: false, data: {sample_id: $('#sample_id').val()}
                    }).responseJSON[0];
                    if (data0 !== undefined) {
                        $('#myModalError').text('错误！！！样本编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                        return
                    }
                } else {
                    // edit
                    url_ajax = url + id + '/';
                    method = 'PUT';
                }

                $.ajax({
                    url: url_ajax,
                    method: method,
                    data: $(this).serialize(),
                    headers: {'X-HTTP-Method-Override': 'PATCH'},
                    success: function () {
                        let v_tmp = $('#sample_id').val();
                        if (type === 'new') {
                            databaseRecordAjaxPut("ClinicalInfo", "单项添加", "样本编号：" + v_tmp);
                            $('#myModalError').text('添加成功！！！样本编号：' + v_tmp);
                        } else {
                            databaseRecordAjaxPut("ClinicalInfo", "单项更新", "样本编号：" + v_tmp);
                            $('#myModalError').text('更新成功！！！样本编号：' + v_tmp);
                        }

                        setTimeout(
                            function () {
                                window.location.reload(true);
                            }, 3000
                        );
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('#myModalError').text('出现错误！！！请联系管理员');
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });

            $('#confirm').on('click', '#delete', function (e) {
                $.ajax({
                    url: url + id + '/',
                    method: 'DELETE',
                    success: function () {
                        databaseRecordAjaxPut("ClinicalInfo", "单项删除", "index：" + id);
                        window.location.reload(true);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });

            $('#new').on('click', function (e) {
                MyModelInit('新增', {});
                $("#myModal").modal();
            });

            $('#upload').on('click', function (e) {
                $('#uploadOperator').val("");
                $('#uploadFile').val("");
                $('#uploadError').val("");
                $('#uploadUrl').val('ClinicalInfo');
                $("#uploadModal").modal();
            });

            $('#bulkDel').on('click', function (e) {
                $('#bulkDelUrl').val('ClinicalInfo');
                $("#bulkDelModal").modal();
            });

            $('.downloadExcel').on('click', function (e) {
                e.preventDefault();
                window.location.href = '/download_excel/ClinicalInfo/'
            });

            $('#myModalReset').on('click', function (e) {
                e.preventDefault();
                if ($('#modal_title').text() === '更新') {
                    MyModelInit('更新', dataModelForm);
                } else {
                    MyModelInit('新增', {});
                }
            });

            pie_plot('ClinicalInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());

            fieldForPie.change(function () {
                pie_plot('ClinicalInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());
            });

            $("#modelForm input[type='text']").focus(function () {
                let key2 = $(this).attr('id');
                let values = $.ajax({
                    url: "{% url 'unique' %}", data: {model: "ClinicalInfo", filed: key2},
                    dataType: 'json', contentType: "application/json",
                    method: "GET", async: false
                }).responseJSON.values;
                console.info("values:", values, "; key2:", key2);
                input_autocomplete(values, '#' + key2);
            });
        })

    </script>
{% endblock %}